//
//  LogisticsManagementViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-8-20.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "LogisticsManagementViewController.h"
#import "Config.h"
#import "Helper.h"
#import "JMFBase.h"
#import "FreightTemplateViewController.h"
#import "AnnouncementViewController.h"
//#import "MJRefresh.h"

@interface LogisticsManagementViewController ()

@end

@implementation LogisticsManagementViewController
{
    UIImageView *_logisticsGuideView;
}

@synthesize dataSource = _dataSource;
@synthesize tableView = _tableView;
@synthesize addButton = _addButton;
@synthesize footer = _footer;
@synthesize header = _header;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //背景
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    self.title = _L(@"vc_title_076");

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT-44.0f) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    _tableView.backgroundColor = _SYS_COLOR_BACKGROUND;
    _tableView.backgroundView = nil;
    _tableView.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    //导航栏左按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    _addButton = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, _SYS_FRAME_HEIGHT-84.0f-5.0f, 300.0f, 40.0f)];
    _addButton.titleLabel.font = _SYS_FONT_009;
    [_addButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_006_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_addButton setTitle:_L(@"btn_yes_37") forState:UIControlStateNormal];
    [_addButton addTarget:self action:@selector(addButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_addButton];
    
    _logisticsGuideView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 50.5f)];
    _logisticsGuideView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_img_008" ofType:@"jpg"]];
    _logisticsGuideView.userInteractionEnabled = YES;
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(guideViewEvent:)];
    [_logisticsGuideView addGestureRecognizer:gestureRecognizer];
    
    _tableView.tableHeaderView = _logisticsGuideView;
    
    _dataSource = [NSMutableArray new];
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = _tableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;
    
    // 5.0.5秒后自动下拉刷新
//    [_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.5];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [_header beginRefreshing];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return _dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        
        cell.textLabel.font = _SYS_FONT_006;
        cell.detailTextLabel.font = _SYS_FONT_003;
        
        UILabel *defaultLabel = [[UILabel alloc] initWithFrame:CGRectNull];
        defaultLabel.backgroundColor = [UIColor clearColor];
        defaultLabel.textColor = [UIColor colorWithRed:171/255.0f green:171/255.0f blue:171/255.0f alpha:1.0f];
        defaultLabel.font = _SYS_FONT_002;
        
        [cell.contentView addSubview:defaultLabel];
        
    }
    
    cell.textLabel.text = _dataSource[indexPath.section][@"name"];
    
    if ([_dataSource[indexPath.section][@"status"] integerValue] == 1) {
        
        CGSize size = [cell.textLabel.text sizeWithFont:_SYS_FONT_006];
        
        ((UILabel *)[cell.contentView subviews][2]).frame = CGRectMake(size.width+15.0f, 7.0f, 100.0f,size.height);
        ((UILabel *)[cell.contentView subviews][2]).text = [NSString stringWithFormat:@"(%@)",_L(@"title_89")];
    }
    else {
        
        ((UILabel *)[cell.contentView subviews][2]).text = @"";
    }
    
    switch ([_dataSource[indexPath.section][@"type"] integerValue]) {
        case 0:
            cell.detailTextLabel.text = _L(@"title_fare_bear_02");
            break;
        case 1:
            cell.detailTextLabel.text = _L(@"title_fare_bear_01");
            break;
        default:
            break;
    }

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FreightTemplateViewController *freightTemplateVC = [[FreightTemplateViewController alloc] initWithTemplateId:[_dataSource[indexPath.section][@"id"] integerValue]];
    freightTemplateVC.title = _L(@"vc_title_095");
    [self.navigationController pushViewController:freightTemplateVC animated:YES];
}


#pragma mark - 事件
- (void)backButtonEvent
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addButtonEvent
{
    FreightTemplateViewController *freightTemplateVC = [[FreightTemplateViewController alloc] init];
    freightTemplateVC.title = _L(@"vc_title_094");
    UINavigationController* freightTemplateNV = [[UINavigationController alloc] initWithRootViewController:freightTemplateVC];
    
    [Helper navigationControllerCommonStyle:freightTemplateNV];
    
    [self.navigationController presentModalViewController:freightTemplateNV animated:true];
}

- (void)guideViewEvent:(id)sender
{
    AnnouncementViewController *announcementVC = [[AnnouncementViewController alloc] initWithUrl:URL_LOGISTICS_GUIDE];
    announcementVC.title = _L(@"vc_title_098");
    announcementVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:announcementVC animated:YES];
}

#pragma mark - 私有方法

//模式切换时，重设布局。在管理模式下才显示出添加按钮，所以tableview或者空页面要腾出适合的空间给按钮。选择模式下就不用显示添加按钮。
- (void)setViewNeedDisplay:(BOOL)managing
{
    if (managing) {

        [UIView animateWithDuration:0.5f animations:^{
            _addButton.alpha = 1.0f;
            _tableView.frame = CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT-44.0f);
            
            if (_dataSource.count == 0) {
                _blankPage.frame = CGRectMake(0.0f, -44.0f, 320.0f, _SYS_FRAME_HEIGHT-44.0f);
            }
        }];
        
    }
    else {
        
        [UIView animateWithDuration:0.5f animations:^{
            _addButton.alpha = 0.0f;
            _tableView.frame = CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT);
            
            if (_dataSource.count == 0) {
                _blankPage.frame = CGRectMake(0.0f, -44.0f, 320.0f, _SYS_FRAME_HEIGHT);
            }
        }];
    }
}

/*!
 @abstract 获取数据源最后一条数据的id
 @discussion 用于分页功能
 @result 数据源最后一条数据的id
 */
- (NSInteger)catchTheLastDataSourceId
{
    if (_dataSource.count < 1) {
        
        return 0;
    }
    
    return [_dataSource[(_dataSource.count - 1)][@"id"] integerValue];
}

- (NSIndexPath *)indexPathForButtonOption:(id)sender
{
    UIButton *d = (UIButton *)sender;
    
    return [_tableView indexPathForCell:(UITableViewCell *)d.superview.superview];
}

/*!
 @abstract 通过数据源是否为空来判断页面的显示
 */
- (void)viewNeedsDisplay
{
    
    if (_dataSource.count == 0) {
        
        _blankPage = [[UIView alloc] initWithFrame:CGRectMake(0.0f, -44.0f, 320.0f, _SYS_FRAME_HEIGHT-44.0f)];
        _blankPage.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 139/2.0f, 137.0f/2.0f)];
        imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_016@2x" ofType:@"png"]];
        imageView.center = _blankPage.center;
        [_blankPage addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, imageView.frame.origin.y+imageView.frame.size.height+10.0f, 300.0f, 50.0f)];
        label.textAlignment = UITextAlignmentCenter;
        label.numberOfLines = 0;
        label.textColor = [UIColor grayColor];
        label.text = _L(@"alert_107");
        [_blankPage addSubview:label];
        
        [self.view addSubview:_blankPage];
        
        _tableView.backgroundColor = [UIColor whiteColor];
        self.view.backgroundColor = [UIColor whiteColor];
    }else{
        
        [_blankPage removeFromSuperview];
        _tableView.backgroundColor = _SYS_COLOR_BACKGROUND;
        self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    }
}

- (void)loadLogisticsDataWithCheckId:(NSInteger)checkId
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_FREIGHT_TEMPLATE_LIST];
    request.delegate = self;
//    request.hudOn = true;
//    request.hudTitle = _L(@"title_loading_01");
    
    //id不为空，说明用户在加载更多
    if(checkId != 0){
        
        [request setValue:[NSNumber numberWithInteger:checkId] forParameter:@"checkId"];
        
        [request setSuccessSelector:@selector(moreLogisticsData:)];
    }
    
    [request asynchronous];
}

//刷新tableview
- (void)reloadTableView
{
    [self.tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if (_dataSource.count != 0) {
            [_dataSource removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
            
            _footer.scrollView = self.tableView;
        }
        
        [self reloadTableView];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
    [self viewNeedsDisplay];
}

- (void)moreLogisticsData:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            
            [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
            
        }
        
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}
//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        //请求初始数据
        [self loadLogisticsDataWithCheckId:0];
    }
    
    //上拉加载更多
    else {
        
        if ([self catchTheLastDataSourceId] != 0) {
            [self loadLogisticsDataWithCheckId:[self catchTheLastDataSourceId]];
        }
    }
}

- (void)dealloc
{
    _dataSource = nil;
}
@end
